<?php
namespace app\mingteng\controller;

use think\Controller;
use think\Session;

class Base extends Controller {
    /**
     * 析构函数
     */
    function __construct()
    {
        Session::start();
        header("Cache-control: private");
        parent::__construct();
        //用户中心面包屑导航
        $navigate_admin = navigate_admin();
        $this->assign('navigate_admin',$navigate_admin);
    }

    /*
     * 初始化操作
     */
    public function _initialize(){
        //过滤不需要登陆的行为
        if(in_array(ACTION_NAME,array('login','logout','verify')) || in_array(CONTROLLER_NAME,array('Ueditor','Uploadify'))){
            //return;
        }else{
            if(session('admin_id') > 0 ){
                $this->check_priv();//检查管理员菜单操作权限
            }else{
                Header("Location:".U('Admin/login'));
            }
        }
        $this->public_assign();
    }

    /**
     * 保存公告变量到 smarty中 比如 导航
     */
    public function public_assign(){
        $tpshop_config = array();
        $tp_config = M('config')->cache(true)->select();
        foreach($tp_config as $k => $v)
        {
            $tpshop_config[$v['inc_type'].'_'.$v['name']] = $v['value'];
        }
        $this->assign('tpshop_config', $tpshop_config);
    }

    public function check_priv(){
        $ctl = strtolower(CONTROLLER_NAME);
        $act = strtolower(ACTION_NAME);
        $act_list = session('act_list');
        //无需验证的操作
        $uneed_check = array('login','logout','vertifyhandle','vertify','imageup','upload','login_task');
        if($ctl == 'index' || $act_list == 'all'){
            //后台首页控制器无需验证,超级管理员无需验证
            return true;
        }elseif(request()->isAjax() || strpos($act,'ajax')!== false || in_array($act,$uneed_check)){
            //所有ajax请求不需要验证权限
            return true;
        }else{
            $role_right = '';
            $right = M('system_menu')->where(array("id"=>array("in", $act_list)))->cache(true)->getField('right',true);
            foreach ($right as $val){
                $role_right .= strtolower($val).',';
            }
            $role = explode(',', $role_right);
          //  pr($role,1);
            //检查是否拥有此操作权限
            if(!in_array($ctl.'@'.$act, $role)){
                $this->error('您没有操作权限['.($ctl.'@'.$act).'],请联系超级管理员分配权限',U('Index/welcome'));
            }
        }
    }
}
